package com.luxsoft.sw3.em2.services;

import org.apache.log4j.Logger;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * Manager q permite administrar los procesos programados
 * 
 * @author Ruben Cancino Ramos
 *
 */
public final class ProcesosManager {
	
	Logger logger=Logger.getLogger(getClass());
	
	private static ProcesosManager INSTANCE;
	
	private ApplicationContext context;
	/*
	public static synchronized ProcesosManager getInstance(){
		if(INSTANCE==null){
			INSTANCE=new ProcesosManager();
		}
		return INSTANCE;
	}*/
	
	private ProcesosManager(){
		getContext();
	}
	
	public static synchronized void close(){
		if(INSTANCE!=null){
			INSTANCE.closeContext();
		}
	}
	
	
	protected String[] getConfigLocations() {
        return new String[] {                
        		"em2-procesos-context.xml"
            };
    }
	
	public ApplicationContext getContext(){		
		if(context==null){
			context=new ClassPathXmlApplicationContext(
					getConfigLocations(),ProcesosManager.class
					);
		}
		return context;
	}
	
	protected synchronized void closeContext(){
		((ClassPathXmlApplicationContext)INSTANCE.getContext()).close();
		context=null;
	}
	
	private Scheduler getScheduler(){
		return (Scheduler)context.getBean("procesosScheduler");
	}
	
	public void puaseTrigger(String jobName) throws SchedulerException{
		getScheduler().pauseJob(jobName, null);
	}
	
	public void startScheduler() throws SchedulerException{
		getScheduler().start();
		
	}
	
	public void stopScheduler() throws SchedulerException{
		getScheduler().shutdown();
	}
	
	public String[] getJobs() throws SchedulerException{
		return getScheduler().getJobNames(null);
	}
	
	public static void main(String[] args) throws SchedulerException {
		/*String[] jobs=ProcesosManager.getInstance().getJobs();
		for(String job:jobs){
			System.out.println(job);
		}*/
		//ProcesosManager.getInstance().startScheduler();
	}

}
